package org.example.study.liaoxuefeng;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: 默苍璃
 * @date: 2023-05-23 18:26
 * <p>
 * wait和notify
 */
public class WaitAndNotify {

    public static void main(String[] args) throws InterruptedException {

        TaskQueue q = new TaskQueue();

        ArrayList<Thread> ts = new ArrayList<Thread>();

        //循环5次  创建5个t线程 处于wait状态
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread() {

                public void run() {
                    System.out.println(Thread.currentThread().getName());

                    // 执行task:
                    while (true) {
                        try {
                            String s = q.getTask();
                            System.out.println("execute task: " + s);
                        } catch (InterruptedException e) {
                            return;
                        }
                    }
                }
            };

            if (i == 0) {
                t.setPriority(Thread.MAX_PRIORITY);
            }

            if (i == 4) {
                t.setPriority(Thread.MIN_PRIORITY);
            }
            t.start();
            ts.add(t);
        }


        //创建add线程
        Thread add = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                // 放入task:
                String s = "t-" + Math.random();
                System.out.println("add task: " + s);
                System.out.println(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getPriority());
                q.addTask(s);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        });

        //启动add线程
        add.start();
        add.join();

        Thread.sleep(100);

        //终止(阻断)线程
        for (Thread t : ts) {
            t.interrupt();
        }

    }

}


/**
 * 任务队列
 */
class TaskQueue {

    Queue<String> queue = new LinkedList<>();


    /**
     * 往 queue 中添加字符串
     *
     * @param s
     */
    public synchronized void addTask(String s) {
        this.queue.add(s);
        this.notifyAll();
    }


    /**
     * 移除 queue 中字符串
     *
     * @return
     * @throws InterruptedException
     */
    public synchronized String getTask() throws InterruptedException {

        System.out.println("getTask____________" + Thread.currentThread().getName());

        while (queue.isEmpty()) {
            this.wait();
        }

        //removeFirst 移除第一条数据
        return queue.remove();
    }

}
